{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2b116b66-8015-4742-8115-bcb0f09a6e10",
   "metadata": {},
   "source": [
    "# Working with an Organization-Wide Dependency Graph"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8fd2570-ff4b-4cec-9269-cbf542cd66af",
   "metadata": {},
   "source": [
    "Version 2.4.1 of the ArcGIS API for Python brought about some exciting new functionality for content management: the [`arcgis.apps.itemgraph`](/python/latest/api-reference/arcgis.apps.itemgraph.html) module. This module, in it's most basic usage, allows you to take an item in an organization and examine the deep dependencies of it- what items it needs to exist, what items those items need to exist, and so on. This is very helpful for management of apps and smaller subsets of org items, but what if we really want to push the limits of what we can do with this module?\n",
    "\n",
    "With a little patience and creativity, we can create an actively-updated dependency graph that encapsulates every item in our organization. Doing so opens up all sorts of doors for us, such as:\n",
    "- The ability to examine the total reverse dependencies of an item (e.g., take a feature layer- we can see every app or map in our org that requires it to exist, or that will be effected by a change to it\n",
    "- Quick identification of all broken dependencies in our organization\n",
    "- Sorting of items in our organization by complexity (most vs. least dependencies)\n",
    "\n",
    "In this sample, we'll provide code to create and update an organization-wide graph, glean information from our graph, and then finally include a section on how to automate this process via ArcGIS Notebooks."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19637729-09c6-4094-8fd4-c7daf9b94299",
   "metadata": {},
   "source": [
    "## Part 1: Creating and Updating an Org-Wide Graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3d4c3a05-240c-4906-9509-75ccaba0c625",
   "metadata": {},
   "outputs": [],
   "source": [
    "from arcgis.gis import GIS\n",
    "from arcgis.apps.itemgraph import create_dependency_graph, load_from_file\n",
    "import datetime\n",
    "import networkx as nx\n",
    "gis = GIS(\"home\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e74b49d1-0290-4634-9313-ceaf3334512e",
   "metadata": {},
   "source": [
    "### Initial Run\n",
    "\n",
    "This builds the initial dependency graph by indexing over every single item in the organization. This only needs to be run once, and will likely take a very long time, depending on how many items are in the org. Once it's been run and the graph structure and time stamp are saved into files, this notebook that updates the dependency graph can be run. This first cell can also be executed outside of ArcGIS Notebooks, and the .gml and .txt files can be brought in from elsewhere.\n",
    "\n",
    "> **Note:** Comment out this cell after the first time running the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0f7d4665-5542-4d80-866b-c10e6081fc3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# only run this cell the very first time you index over your org and grab all the dependencies\n",
    "# this will take a long time if the org has a ton of items\n",
    "\n",
    "import datetime\n",
    "items = gis.content.search(\"\", max_items = 10000)\n",
    "timestamp = int(datetime.datetime.now().timestamp()) * 1000\n",
    "graph = create_dependency_graph(gis, items)\n",
    "graph.write_to_file(\"/arcgis/home/graph_data/updating_graph.gml\")\n",
    "with open(\"/arcgis/home/graph_data/updating_timestamp.txt\", \"w\") as file:\n",
    "    file.write(str(timestamp))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adf0a4ab-8fc1-4152-bd96-82f88bb219d1",
   "metadata": {},
   "source": [
    "Now, we have a snapshot of every item in the organization and how they relate to one another. But, what if we don't want to run this lengthy initial step every time we want to work with this graph? And what if there are items that are getting created, updated, and deleted, so the relationships in this graph might become outdated? This notebook will go over how we can use specific capabilities of the ItemGraph to examine massive graphs without re-indexing, and will include code that will update the graph through automation, meaning that scheduling this notebook to run will ensure that your organization-wide dependency graph stays up to date."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4146031-7653-4d06-b2b6-563048535186",
   "metadata": {},
   "source": [
    "### Efficiently Analyzing the Existent Graph\n",
    "\n",
    "This workflow is predicated on preserving our graph offline in a [GML format file](https://networkx.org/documentation/stable/reference/readwrite/gml.html), which is a commonly used file type for storing graph structures. Our [`write_to_file()`](/python/latest/api-reference/arcgis.apps.itemgraph.html#arcgis.apps.itemgraph.ItemGraph.write_to_file) function generates a .gml file with both the basic graph structure and some additional metadata that informs our [`load_from_file()`](/python/latest/api-reference/arcgis.apps.itemgraph.html#arcgis.apps.itemgraph.load_from_file) function how to grab a given item from a GIS organization.\n",
    "\n",
    "When loading up an existent graph based on a .gml file, it still may take some time to retrieve every single item associated with each node in the graph, especially for organizations with thousands and thousands of items. If you want to instantly analyze the items and relationships in a .gml file with thousands of records, we can call `load_to_file()` and elect to *not* retrieve each item. This still gives us the power to view all item id's and their dependencies in the org, but without the overhead of retrieving each one from a REST endpoint first. Users can simply retrieve the associated items as needed, based on the id's.\n",
    "\n",
    "We'll show a quick example of this using the existent graph, and then use a graph loaded with the items to ensure we're up-to-date with the current state of organization. We'll only print the first few for the sake of keeping this page short."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "63d6a566-4e5d-495f-b448-cf452db3f967",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3643"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fast_graph = load_from_file(\"/arcgis/home/graph_data/updating_graph.gml\", gis, False)\n",
    "len(fast_graph.all_items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "08e88638-8b71-4340-b912-88e0b5d71ddd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ItemNode(id: 72c2671bff1143c4bc577755bc00a7aa),\n",
       " ItemNode(id: 405b512903e74ec0af5ce2083b863705),\n",
       " ItemNode(id: 039e2c7e648b4a5d9d64c57b470d7397),\n",
       " ItemNode(id: 64a096654b924b2998ed07a747524e96),\n",
       " ItemNode(id: e12e8599965c43af9632a5c9633c2994),\n",
       " ItemNode(id: 5b534fa4a26d4fd1868ea7509806b053),\n",
       " ItemNode(id: 96cf6c756ee74c288a8a88788f980266),\n",
       " ItemNode(id: 64480b5bfc474ab1a464fa18098c92e5),\n",
       " ItemNode(id: 14d12cc813b2422db0f4b7b1b701bcc1),\n",
       " ItemNode(id: 5a1a8ac568a942b792c1283b7acff602),\n",
       " ItemNode(id: dc5014dff7014a23af6eff25b492bce6),\n",
       " ItemNode(id: 1fcbf4e77ebc46ef9971d1194f412c3b),\n",
       " ItemNode(id: fc02404cdda24f72842d34b28267d77a),\n",
       " ItemNode(id: 4cc1488a3c134af9abbe0a268d50b499),\n",
       " ItemNode(id: 24ca75398c494dad8b4e7104e2a640d5),\n",
       " ItemNode(id: 4839158f96544bafb841c1739d84f11b),\n",
       " ItemNode(id: 9b9de0ff974e4924b15bc278ad6d6676),\n",
       " ItemNode(id: 87c2394212ad42bcb89de9e244d4072d),\n",
       " ItemNode(id: 13697d5ab62449e78dd9c28037380592),\n",
       " ItemNode(id: a93fd45749ec4773839f02623ebad01d)]"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fast_graph.all_items()[:20]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8a3c2f4b-c416-4ef5-bb22-a1d24a628da8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n",
       "                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n",
       "                       <a href='https://pythonapitestnb.dev.geocloud.com/portal/home/item.html?id=72c2671bff1143c4bc577755bc00a7aa' target='_blank'>\n",
       "                        <img src='' width='200' height='133' class=\"itemThumbnail\">\n",
       "                       </a>\n",
       "                    </div>\n",
       "\n",
       "                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n",
       "                        <a href='https://pythonapitestnb.dev.geocloud.com/portal/home/item.html?id=72c2671bff1143c4bc577755bc00a7aa' target='_blank'><b>Latin America</b>\n",
       "                        </a>\n",
       "                        <br/> <br/><img src='https://pythonapitestnb.dev.geocloud.com/portal/home/js/jsapi/esri/css/images/item_type_icons/layers16.png' style=\"vertical-align:middle;\" width=16 height=16>Mobile Map Package by esri_nav\n",
       "                        <br/>Last Modified: October 01, 2017\n",
       "                        <br/>0 comments, 0 views\n",
       "                    </div>\n",
       "                </div>\n",
       "                "
      ],
      "text/plain": [
       "<Item title:\"Latin America\" type:Mobile Map Package owner:esri_nav>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "random_node = fast_graph.all_items()[0]\n",
    "gis.content.get(random_node.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d0d126a-8b82-4b52-ab64-b9fb8231a836",
   "metadata": {},
   "source": [
    "As we can see, we can instantly load in this complicated graph and just grab the `Item` associated with a given node as needed. However, for this next part, we're going to need to retrieve everything in the graph, which could take a while; that's why it's meant for some scheduled automation.\n",
    "\n",
    "### Automation: Updating our Org-Wide Graph\n",
    "\n",
    "The items in our org might not be the same as the ones we had in it yesterday- that's why we want to update our graph periodically. The `ItemGraph` class is an extension of [NetworkX's DiGraph class](https://networkx.org/documentation/stable/reference/classes/digraph.html), meaning we get all sorts of handy functions and ways to manipulate our graph built in. We can use some attributes of the `ItemGraph` class and some networkx tricks to maintain an up-to-date record of everything in the org.\n",
    "\n",
    "We'll start by loading up our existent graph stored in the .gml file with every `Item` attached. This may take a while to do, depending on how many items must be retrieved. We retrieve the items so that later we can verify which ones still exist and which ones have been deleted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ccf52250-3b9e-47e2-bcb2-81d82473d515",
   "metadata": {},
   "outputs": [],
   "source": [
    "# grab the graph created yesterday to update it\n",
    "old_graph = load_from_file(\"/arcgis/home/graph_data/updating_graph.gml\", gis, True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cfe9d923-1528-4e9c-9ffb-d48783bcd977",
   "metadata": {},
   "source": [
    "Keeping timestamps allows us to understand when the last time we updated the graph was and maintain an accurate graph. This approach allows for the scheduling of this notebook on any timeframe- whether you run it every day, every week, every month, or something else."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9c3989f2-7047-48dc-ac27-e941f8cc0f3b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# grab our old and new timestamps\n",
    "# old is the last time we updated the graph, new is current time\n",
    "with open(\"/arcgis/home/graph_data/updating_timestamp.txt\", \"r\") as file:\n",
    "    old_timestamp = int(file.read())\n",
    "new_timestamp = int(datetime.datetime.now().timestamp()) * 1000\n",
    "\n",
    "# use these timestamps to see items that have been modified or created since last run\n",
    "q = f\"modified: [{old_timestamp} TO {new_timestamp}]\"\n",
    "modified_items = gis.content.search(query = q, sort_field = \"modified\", sort_order = \"desc\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "1dcbf4d7-02e0-471c-bd64-8e69e0462a96",
   "metadata": {},
   "outputs": [],
   "source": [
    "# now that we have our list of updated items, make a graph out of them\n",
    "mod_graph = create_dependency_graph(gis, modified_items)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9a664b7-6bc8-46e5-b8e9-3972d371508e",
   "metadata": {},
   "source": [
    "Now we have a graph containing only new/modified items, and all of their dependencies. We'll have to combine the new information in this graph with our existent graph, and delete the outdated information. Time for some fun graph operations!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9605f93b-b732-4379-9636-b2e9340d57b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# nx.compose() combines all nodes and relationships of two graphs\n",
    "new_graph = nx.compose(old_graph, mod_graph)\n",
    "\n",
    "# find the list of items in both graphs\n",
    "# these are ones that already existed but were modified, meaning dependencies might have changed\n",
    "intersects = set(old_graph.all_items('id')) & set(mod_graph.all_items('id'))\n",
    "\n",
    "# go through these items and delete outdated forward dependencies\n",
    "for itemid in list(intersects):\n",
    "    old_contains = set(old_graph.get_node(itemid).contains(\"id\"))\n",
    "    mod_contains = set(mod_graph.get_node(itemid).contains(\"id\"))\n",
    "    \n",
    "    # isolate deps that only existed in old graph\n",
    "    outdated = old_contains - mod_contains\n",
    "\n",
    "    # remove these relationships from the new graph\n",
    "    for dep in list(outdated):\n",
    "        new_graph.delete_relationship(itemid, dep)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2d76e7f6-2c07-4c45-9f3a-37112d3f26d9",
   "metadata": {},
   "source": [
    "Our `new_graph` now has an accurate reflection of all item relationships in our organization- any item that got changed could have had it's forward dependencies altered, so we made sure that those got updated to reflect any changes. We didn't have to worry about changing any reverse dependencies, since every reverse dependency is still just a forward dependency for another item, so the appropriate relationship was addressed during that process.\n",
    "\n",
    "We have one more little housekeeping thing to do with this new graph now- due to the way that `nx.compose()` works, the individual nodes within the new graph still contain references to the old graph. We just have to make sure those nodes now use the new graph for any computation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "730ad8cc-a7a9-4e3f-8088-015b5e59790e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# make sure our nodes are all referencing the new updated graph\n",
    "for node in new_graph.all_items():\n",
    "    node.graph = new_graph"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4db9c02d-b77f-42e6-bc31-250055ff1846",
   "metadata": {},
   "source": [
    "Alright, awesome, now we have all newly created or recently modified items accounted for- but we still have to account for items that might have been deleted. How do we do this? \n",
    "\n",
    "Remember when we ran the `load_from_file()` function earlier that retrieved all of the items while rebuilding the graph? Well, any node of an item that's been deleted won't have an attached `Item` object anymore, since it wouldn't have been retrieved. Therefore, if we have a node with no associated item, we can assume the item has been deleted, and that if the node is not contained by another node, then the item is not still meant to exist. So, we can delete nodes from our graph that fit that criteria.\n",
    "\n",
    "One added layer of complexity: what if the node of a deleted item is contained by another node of a deleted item that just hasn't been processed yet? We can avoid this scenario by sorting our nodes in ascending order of how many items they're required by, ensuring we're prioritizing processing ones furthest up the dependency chains first (e.g., deleted item A contains B which contains C- if we analyze B or C first, we'll wrongfully keep them, but if we start with A and go down the chain, all will get deleted properly)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "96cea807-c561-4408-aa42-4153d752fc98",
   "metadata": {},
   "outputs": [],
   "source": [
    "nodes = new_graph.all_items()\n",
    "\n",
    "# define our sort function\n",
    "def count_reqs(node):\n",
    "    return len(node.required_by(\"id\"))\n",
    "\n",
    "# this orders our nodes properly\n",
    "sorted_nodes = sorted(nodes, key=count_reqs)\n",
    "\n",
    "# remove ones that don't have items and aren't dependencies of others\n",
    "for node in sorted_nodes:\n",
    "    if not node.item and not node.contained_by():\n",
    "        new_graph.remove_node(node.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d89a380c-1f85-4326-8372-37b74bb5aa00",
   "metadata": {},
   "source": [
    "And there we have it. Now we have a properly updated graph, one that reflects today's state of every item and their dependencies. Grabbing a node for a given item from `new_graph` should give you a holistic look of all items it relates to in an org, no matter if it's an immediate or deep relationship in either direction. To summarize, we:\n",
    "\n",
    "- Loaded in the graph from the last time we ran the notebook\n",
    "- Determined what items had been modified/created since the last time we ran the notebook\n",
    "- Created a graph from those updated items, capturing their current dependencies\n",
    "- Merged the old graph with the modified graph to create a new graph with all nodes/relationships from both graphs\n",
    "- Got rid of relationships that no longer existed from the new graph\n",
    "- Got rid of any items that had been deleted and weren't dependencies of an item from the new graph\n",
    "\n",
    "Now, we'll write out the state of this graph and the timestamp at which we started everything, so we can repeat this process in the future and continue to update our graph as the items in our ArcGIS organization evolve."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "ef2845ff-c2cd-428d-9ff4-486ed0c8160c",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_graph.write_to_file(\"/arcgis/home/graph_data/updating_graph.gml\")\n",
    "with open(\"/arcgis/home/graph_data/updating_timestamp.txt\", \"w\") as file:\n",
    "    file.write(str(timestamp))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08f5ef15-cf3f-4317-bca6-794761166f70",
   "metadata": {},
   "source": [
    "## Part 2: Using the Graph"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "587f19ea-923c-4001-ad87-5dde5129b99b",
   "metadata": {},
   "source": [
    "Now that we have our organization-wide graph and know that it's up to date, we can use it for some useful administration and analysis. We'll take a look at the three things mentioned in the intro: examining comprehensive reverse dependencies of items, identifying broken dependencies that need fixing, and sorting our items based on their complexity."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b60c0fc9-4523-4a93-bf0a-47be12ff689a",
   "metadata": {},
   "source": [
    "### Comprehensive Reverse Dependencies\n",
    "\n",
    "This is a very powerful perk of having every relationship in an organization included in a graph: the ability to see _every_ single item that relies on a specific item. Say you have a feature layer that is used in numerous maps and applications throughout your org: you can instantly acquire a list of every one that consumes it, either directly or indirectly. Let's take a look."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "35636665-42d0-486d-a1bc-e9aae10bed2c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div class=\"item_container\" style=\"height: auto; overflow: hidden; border: 1px solid #cfcfcf; border-radius: 2px; background: #f6fafa; line-height: 1.21429em; padding: 10px;\">\n",
       "                    <div class=\"item_left\" style=\"width: 210px; float: left;\">\n",
       "                       <a href='https://pythonapitestnb.dev.geocloud.com/portal/home/item.html?id=7dc6cea0b1764a1f9af2e679f642f0f5' target='_blank'>\n",
       "                        <img src='https://pythonapitestnb.dev.geocloud.com/portal/portalimages/desktopapp.png' class=\"itemThumbnail\">\n",
       "                       </a>\n",
       "                    </div>\n",
       "\n",
       "                    <div class=\"item_right\"     style=\"float: none; width: auto; overflow: hidden;\">\n",
       "                        <a href='https://pythonapitestnb.dev.geocloud.com/portal/home/item.html?id=7dc6cea0b1764a1f9af2e679f642f0f5' target='_blank'><b>World Topographic Map</b>\n",
       "                        </a>\n",
       "                        <br/>This vector tile layer provides a world topographic map. (World Edition)<br/><img src='https://pythonapitestnb.dev.geocloud.com/portal/home/js/jsapi/esri/css/images/item_type_icons/layers16.png' style=\"vertical-align:middle;\" width=16 height=16>Vector Tile Layer by esri_livingatlas\n",
       "                        <br/>Last Modified: April 26, 2025\n",
       "                        <br/>0 comments, 0 views\n",
       "                    </div>\n",
       "                </div>\n",
       "                "
      ],
      "text/plain": [
       "<Item title:\"World Topographic Map\" type:Vector Tile Layer owner:esri_livingatlas>"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# grab a node corresponding to a feature layer\n",
    "flayer_id = \"7dc6cea0b1764a1f9af2e679f642f0f5\"\n",
    "flayer_node = new_graph.get_node(flayer_id)\n",
    "flayer_node.item"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51ccb876-369a-4636-9112-f0f9c39b94b0",
   "metadata": {},
   "source": [
    "Calling `.contained_by()` will show all of the items that contain our vector tile layer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "cb088e78-1ffa-4b89-ac4e-25526b372388",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<Item title:\"National Day1 - With Created Layer\" type:Web Map owner:arcgis_python>,\n",
       " <Item title:\"National Day1 - With Created Layer\" type:Web Map owner:arcgis_python>,\n",
       " <Item title:\"AZ and NM Cities\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"Topographic\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"Living Atlas Map\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"Capital Map\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"New York Enriched Top Areas of Interest\" type:Web Map owner:arcgispyapibot>,\n",
       " <Item title:\"New York Enriched Top Areas of Interest\" type:Web Map owner:arcgispyapibot>]"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "flayer_node.contained_by(\"item\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6328f75-6018-4c7a-b275-2ebfded5985f",
   "metadata": {},
   "source": [
    "Calling `.required_by()` will show us all of the items that depend on our layer in some way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "e0af9dea-2b2b-46ca-a9ee-faff7e7c6b90",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[<Item title:\"All About Arizona and New Mexico\" type:StoryMap owner:nparavicini>,\n",
       " <Item title:\"National Day1 - With Created Layer\" type:Web Map owner:arcgis_python>,\n",
       " <Item title:\"Living Atlas Map\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"Ruff Ruff\" type:StoryMap owner:nparavicini>,\n",
       " <Item title:\"Capital Map\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"New York Enriched Top Areas of Interest\" type:Web Map owner:arcgispyapibot>,\n",
       " <Item title:\"Topographic\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"AZ and NM Cities\" type:Web Map owner:nparavicini>,\n",
       " <Item title:\"National Day1 - With Created Layer\" type:Web Map owner:arcgis_python>,\n",
       " <Item title:\"Copy this story\" type:StoryMap owner:arcgis_python>,\n",
       " <Item title:\"New York Enriched Top Areas of Interest\" type:Web Map owner:arcgispyapibot>,\n",
       " <Item title:\"San Diego Parrot Sightings\" type:Form owner:nparavicini>,\n",
       " <Item title:\"Testing Copy Content\" type:StoryMap owner:arcgispyapibot>]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "flayer_node.required_by(\"item\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4df1dfe-a652-4655-a60b-694877f9f9a9",
   "metadata": {},
   "source": [
    "There we have it- we instantly determined which items would be affected by deleting or changing our layer."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1c1bdf8-834e-4e8c-b7ad-c513e3593814",
   "metadata": {},
   "source": [
    "### Finding Broken Dependencies\n",
    "\n",
    "In this context, we're calling an item that is contained by another item, but isn't valid or accessible, a \"broken\" dependency- these sorts of items can lead to rendering or logic issues in applications such as Web Maps, StoryMaps, Experiences, Surveys, and so on. There can be a number of reasons for why these improper dependencies may exist- an item being used by an application mistakenly got deleted, there was some sort of corruption with data, the json structure of an application might have been copied from one in a different org, and so on.\n",
    "\n",
    "Luckily, the way the `ItemGraph` is constructed allows us to instantly find these cases where something is potentially awry. During construction of the graph, the ID of each `ItemNode` was passed into the GIS org to see if it yielded an item. Therefore, any node that doesn't have an `.item` property could potentially be a problem."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "d50fcf1d-107f-4bbf-a21f-3ebcfd0c0fb2",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ItemNode(id: 370b95fdf676475ca8fd184ad0931610),\n",
       " ItemNode(id: 1dc6042bb3ba409c9d1eb1d7c996d6ed),\n",
       " ItemNode(id: bf08d46ab087435aa4afbc62092223cb),\n",
       " ItemNode(id: 123hehethiswontwork),\n",
       " ItemNode(id: 2fe20a161c514e16b805a21a7e2d636b),\n",
       " ItemNode(id: 15efb8c0d9e3447782789592f432fc1a),\n",
       " ItemNode(id: bda2f1dc3c824c3e97f4a682554177cf),\n",
       " ItemNode(id: bbf4d26d7c3340dab009c7164cc3e1e5),\n",
       " ItemNode(id: d60affb34dd948a1b973da076830ad00),\n",
       " ItemNode(id: 1182ef6f62a543fdba4a55c85c014431),\n",
       " ItemNode(id: f32924d7b16f41d78839dba3b943b08c),\n",
       " ItemNode(id: 9f91d4c34f194da793c8573b24a751a9),\n",
       " ItemNode(id: 91fa101048bb4855970f7d004a4542ce),\n",
       " ItemNode(id: 6e02b538bea841ed858ef9f52709b655),\n",
       " ItemNode(id: 878802f78aad4ab5a83c1397c72048c5),\n",
       " ItemNode(id: f1801a1b3d674de7b9de246a126eb17b),\n",
       " ItemNode(id: 2),\n",
       " ItemNode(id: 44c3348139a84423b4a46074a104efdf),\n",
       " ItemNode(id: 74ab88e7e22d4dbd93b43a00b2d0155b),\n",
       " ItemNode(id: 306cf223a2fd46d3bf6ce39225681977),\n",
       " ItemNode(id: 1ee3200825ce448c91a1ec9ae4f70c28),\n",
       " ItemNode(id: 72224efc9e044001934bb3be87120beb),\n",
       " ItemNode(id: 90ff936dc4704a0798f61ebbb1dec357),\n",
       " ItemNode(id: 0df19d2d940b47658857cc2fc9623840),\n",
       " ItemNode(id: cdf23b869e7649469759cf756c1d43f0),\n",
       " ItemNode(id: a5f11273b85d40adbd7cf9a162f81ef2),\n",
       " ItemNode(id: 08a9b819b9e04de9a68418f2b225ec6a),\n",
       " ItemNode(id: f265c79c47a3413b8b8f711909f03fe2),\n",
       " ItemNode(id: 819ee7ddbf5848889effd0fa6b039a51),\n",
       " ItemNode(id: 8548e23d8b1a478eaf2246e6fc3b31b9),\n",
       " ItemNode(id: f97edbe48af7427f8604f20320e2de52),\n",
       " ItemNode(id: b66792b3bb004fa8997fcfcef991e984),\n",
       " ItemNode(id: 9204269c8e714500a565a3ddf055825d),\n",
       " ItemNode(id: 28dae0b8f1c44814b281b71752453c61),\n",
       " ItemNode(id: d15c117e60dd4fe299ec03a379c9caf8),\n",
       " ItemNode(id: 3b6d38a456164adea4c061a2a51d89b1),\n",
       " ItemNode(id: a12fcbe07c8d41f1b6981f33a10d1d0c),\n",
       " ItemNode(id: ae4bea7c35824bf1ae571783142dc97d),\n",
       " ItemNode(id: 8e969d9adb7f485c88a8350d317e8c9b),\n",
       " ItemNode(id: 493db5d6832b44a581547a8df8c3907c),\n",
       " ItemNode(id: ebe640ee5d344bea9fca7bfa4d80bb3a),\n",
       " ItemNode(id: 6595a5cf08d64212a85ce9dc47700575),\n",
       " ItemNode(id: 761e9fcf5efa4b368716fae9a1ffda0f),\n",
       " ItemNode(id: 39f0fc3c5b424d679c2ef9ae67e71624),\n",
       " ItemNode(id: 59835c8d71d94475ae04f540a8167343),\n",
       " ItemNode(id: 5b2e49a83dd9427abf398aeeecc00f75),\n",
       " ItemNode(id: dcf4a23abb614d7db9cda2dce90cc528),\n",
       " ItemNode(id: 1d250ce2c5c0463abe0e1887597cc926),\n",
       " ItemNode(id: e57b96c732cc4c34830756d53c8f3619),\n",
       " ItemNode(id: 79f3399102ce4ab79bed0407b03005fc),\n",
       " ItemNode(id: 872d78b038d342b98b6a3547ed8a7ac9),\n",
       " ItemNode(id: 3a2d7671322e4dcbb386e4b961e28c27),\n",
       " ItemNode(id: 8900b18d92ac43cfae142a5a5ad91e4a),\n",
       " ItemNode(id: ba6575ad916041a89887309492473b42),\n",
       " ItemNode(id: 5bbbe8978d9f43a0a7a947b5af3cdc1d),\n",
       " ItemNode(id: 73196ca49b6b40c0a03206663cb10554),\n",
       " ItemNode(id: 9566f596ba404a05aa8eae9221bce82a),\n",
       " ItemNode(id: c2e2b6eaea3740059546951c16af5151),\n",
       " ItemNode(id: 4cee55fa5973406596359e7630ab167e),\n",
       " ItemNode(id: 086eb0c799794d4b99a95a39cd43dca2),\n",
       " ItemNode(id: 6313031ddbe14d7ca0358c4ba8011b27),\n",
       " ItemNode(id: bc68a4d142fb4801a2401a0a5a551ba1),\n",
       " ItemNode(id: 07b7fe74b02c40afa1551d41f19f6d99),\n",
       " ItemNode(id: 632d3de849224fcb990f6d9feae36331),\n",
       " ItemNode(id: 26e87527293b43978b1fb4a24133ead1),\n",
       " ItemNode(id: efff5de20fd546de94e613fbed730372),\n",
       " ItemNode(id: 401d890c10d94e88948a0bd5f82e7559),\n",
       " ItemNode(id: 8cf058d7e58d4f66831e8bc7ae7addbd),\n",
       " ItemNode(id: fed737361fcf4815b2b62651e1cd2a57),\n",
       " ItemNode(id: 46472e81856c4420aeb091e6f0fd24e8),\n",
       " ItemNode(id: d1414cb87c2d41099cfcfe55aa8344e2),\n",
       " ItemNode(id: c2f21b0e86de49fa9b6437cd72779488),\n",
       " ItemNode(id: 77efb9bd7831430ab3788741d327e5df),\n",
       " ItemNode(id: 633c43f3c0e148dea129d6ca49e7fd22),\n",
       " ItemNode(id: 3dce15e4178a4a9c92cacb66f2f7f1ea),\n",
       " ItemNode(id: 2a6e5de8aa4a40899e44017121c5cd89),\n",
       " ItemNode(id: bccbd571d0d54e45b6a69ca0249e7132),\n",
       " ItemNode(id: c8cbf786be774df7b064f149c5898fef),\n",
       " ItemNode(id: 71276e9e9638459890a3072df64e31b6),\n",
       " ItemNode(id: a06302053b3f4e35961584d5818bf1f2),\n",
       " ItemNode(id: 5feee1e7f41a4c47b3f137457c130182),\n",
       " ItemNode(id: 6e403956c5d7419b9c0628e65bed0769),\n",
       " ItemNode(id: 196b5b2798204de38b6dd125823bd714),\n",
       " ItemNode(id: 88ba2cd25d1c423c808fa2e1941a540b),\n",
       " ItemNode(id: c1e6eb63502c4012bb631097b69aefad),\n",
       " ItemNode(id: 4c56c5e083544decbd8d61f3a0bc5a67),\n",
       " ItemNode(id: 905567641b10499ba6a77a0a6e4e5f13),\n",
       " ItemNode(id: 861096f2cb274134bcdca7e875899d69),\n",
       " ItemNode(id: 3afb37e1c7784a05b7d0b4c4c98088c1),\n",
       " ItemNode(id: ae5179630d714200893cda3a6e50e460),\n",
       " ItemNode(id: 2243cb05a01f43cc8d7439447ffe3bbf),\n",
       " ItemNode(id: 27d2f0ad1c7545e48848b43bbd51581a),\n",
       " ItemNode(id: 9dc85299a77540b0bac1507ce67e9dfa),\n",
       " ItemNode(id: 16ffb93988c94d699b672d837c1e03e6),\n",
       " ItemNode(id: 3668c924551b4ff2a508cd2cda897abe),\n",
       " ItemNode(id: c2e075d098a6493393dc3f55876d48f4),\n",
       " ItemNode(id: 53071c1408d240c1997a3779c48467b4),\n",
       " ItemNode(id: 36a01f823259430197c896ff415ee493),\n",
       " ItemNode(id: 21e0d7322928434d8889eba70e4c645a),\n",
       " ItemNode(id: 3e5ba2fec29f4f25afd5a5dbfaadf136),\n",
       " ItemNode(id: d79cd0205b03479b8019648e1dd057f4),\n",
       " ItemNode(id: 8461fdc33b554ffbad1ba54afd1ff499),\n",
       " ItemNode(id: 940e3b1543bf4289822790a15e66c5a4),\n",
       " ItemNode(id: 15e70e3da80b42fd9b60eda8cd6e7cd4),\n",
       " ItemNode(id: 4438ff8fb9174783934412c1c51f4865),\n",
       " ItemNode(id: db089afa931a4a9fb1cb2afe33a6c2f6),\n",
       " ItemNode(id: ba0ff62d9aaf4f628eb1a869c0bb5ee0),\n",
       " ItemNode(id: d50ecf25a35a4cd9baaa1ba7035f77da),\n",
       " ItemNode(id: 76e505d722f64fa6b0debd0f196c3ae1),\n",
       " ItemNode(id: dfcdd3b0495d4f4cb3c3a4a401616d6e),\n",
       " ItemNode(id: 03bcd4dfbeae4a91ae270a934fa27e1b),\n",
       " ItemNode(id: 1c5e01156f5a4f0fae4dc61297785c1d),\n",
       " ItemNode(id: 16d1d5083719466487007bf90313184f),\n",
       " ItemNode(id: 2f87efbdf4ec4942ad610fe4b6bd8c36),\n",
       " ItemNode(id: 97162f48110d4458820c3b66de375d67),\n",
       " ItemNode(id: e98bc26706ba46c782c03c81c739a065),\n",
       " ItemNode(id: 8d721aaa69aa4715911693fa4863b7cf),\n",
       " ItemNode(id: 7a238f29b99f4ff1957e3a469177c56a),\n",
       " ItemNode(id: ff9cafd475ff4a0abf5d8f3a34fc7646),\n",
       " ItemNode(id: ae00236efed94d0b8739ef8a244cc312),\n",
       " ItemNode(id: 12b7fd7eaefc4f40b2fe003604153b3c),\n",
       " ItemNode(id: 1f2248e4464b4065a864cc6aab7aa780),\n",
       " ItemNode(id: c13634e58a024cae9de6a15a4b3eb101),\n",
       " ItemNode(id: bd6943458948460a8eb71d97baaa2ada),\n",
       " ItemNode(id: 6fafb84fc46d4b9c8b25fb57dd9911a2),\n",
       " ItemNode(id: c209e14b44b7420cb40ed650cfefa4f5),\n",
       " ItemNode(id: 048de0545a834d8b8c31a6e0e10270d7),\n",
       " ItemNode(id: 40bf682bf17c4c32a5acade2d54eafb9),\n",
       " ItemNode(id: e608d5be1b4241cdbb1fbf61418513d6),\n",
       " ItemNode(id: 908ceeaa2e5e4ef19e823715a35ab978),\n",
       " ItemNode(id: 7d907c5ac31b4da098d47922bb31f2aa),\n",
       " ItemNode(id: 5dd87bebb9864dac9c2f42604bb79b14),\n",
       " ItemNode(id: 78186ce321f1433091aeb2593abbc565),\n",
       " ItemNode(id: cb7a89a516e84af7b3d7e551a38afed5),\n",
       " ItemNode(id: 6b63dafabf4e486183c21bede31b149e),\n",
       " ItemNode(id: a962b03a45d9415ea97b96eaab7f20d6),\n",
       " ItemNode(id: ac96d6152ba34373ac1c7288b2fcefe4),\n",
       " ItemNode(id: d0d5d3caafed43cd9ce18b9a2609fc5f),\n",
       " ItemNode(id: d9b8675be48d49078db4c55208a0d19e),\n",
       " ItemNode(id: 2defd52c9e4f4759ba085f339d284cd4),\n",
       " ItemNode(id: 961434231c034930801f5b3237715587),\n",
       " ItemNode(id: af83304d94cd4e0da83318f76cde60c4),\n",
       " ItemNode(id: 85179dd8a0fe4ea597586fed851bdeff),\n",
       " ItemNode(id: d5e20e6f7a9542d5ace62983699d3212),\n",
       " ItemNode(id: e3e1712a046d4feeb454e5538a6049d7),\n",
       " ItemNode(id: 045ba64dd5bc4b1a94350f897de956cf),\n",
       " ItemNode(id: 4fb8f3f5422d4a7696b0f8136a4b48aa),\n",
       " ItemNode(id: 75113e1eb7e045229c2cb2698e43114c),\n",
       " ItemNode(id: 228834a1eff64c629c80d0b638f9e43c),\n",
       " ItemNode(id: 42b653e394104606987cbf4b6d1587f9),\n",
       " ItemNode(id: 2c82e7cf420b4026b875ad45750c7a24),\n",
       " ItemNode(id: f1894e0262e44dd6adadef875577d8aa),\n",
       " ItemNode(id: 4f93f1fbebdd4f66a55b6a02f332fa20),\n",
       " ItemNode(id: caa4a0e4ddcb47c9845eb92f024fcd7f),\n",
       " ItemNode(id: 1a9c7b34467d41728f9472a0b6628841),\n",
       " ItemNode(id: 7f4342f006a44c8780d8df79d5da5652),\n",
       " ItemNode(id: a90891b098034e0d928fc4ee30dec1a3),\n",
       " ItemNode(id: caa7ab7f82ab41dd9af1215c11f55a8f),\n",
       " ItemNode(id: bb46d017f7af49728d5af8d8eec43c4e),\n",
       " ItemNode(id: a5df7d4a77c24fc39a1115122370cd8f),\n",
       " ItemNode(id: 879921e888a14e96b5f5b339af907acd),\n",
       " ItemNode(id: 8dd1b1b7731c49839489e0d30146f513),\n",
       " ItemNode(id: eb0499aeb1d5461f877e9b40534e225e),\n",
       " ItemNode(id: 4138c0fbe6b446fbad5447ecc34c8ab8),\n",
       " ItemNode(id: e2ee852f11c14d99814dd4ed42a0a16c),\n",
       " ItemNode(id: e27013ac9f664054a044edd3567c763a),\n",
       " ItemNode(id: ee527fed605a4088b10c49ab9c9ed096),\n",
       " ItemNode(id: a7cdce7ebb404ae6b700b491f21b3243),\n",
       " ItemNode(id: e0dfd02f8f61479c8e1a276c79cafcd5),\n",
       " ItemNode(id: 3d0d28a295e54d25966e7945e2bf5d8e),\n",
       " ItemNode(id: d8e9dfe815b44c8ab3e94a6dc1fcf201),\n",
       " ItemNode(id: 3ce93787d12645f386d42d57ca57c1b4),\n",
       " ItemNode(id: 9c03b76829464ee68d4e6af241cebd5e),\n",
       " ItemNode(id: 5707b86b5f3f4b7c9e67ac2fd317254a),\n",
       " ItemNode(id: 79719a8a27d3440d9d622041ff7b8506),\n",
       " ItemNode(id: 1adc07ec24774989873cafc6c68c1536),\n",
       " ItemNode(id: 1926c33e9bf34ef99b8950f1408368a3),\n",
       " ItemNode(id: 892a696bf2aa4a899f5177017d998156),\n",
       " ItemNode(id: 57654725661049eba50bca930ae786e8),\n",
       " ItemNode(id: c85179865e0c45089e0f9bb29b7ca83e),\n",
       " ItemNode(id: b9cb2d66aaa04093950683767c8eaff0),\n",
       " ItemNode(id: c9b04902a93c4aeda9b92e45b303fe01),\n",
       " ItemNode(id: 1c8354e6f69e4df1969befae339412c7),\n",
       " ItemNode(id: ed2246c081ee49369024cfb312e34899),\n",
       " ItemNode(id: 6d6bae1a02484353add60ddefaca185e),\n",
       " ItemNode(id: a143d4fe84e14712bfd28e71b26ac868),\n",
       " ItemNode(id: d822827df8f345d280ebf2c2be8a48a1),\n",
       " ItemNode(id: 3f4789f0a58b4cdcab5b7d1a08f5f9d9),\n",
       " ItemNode(id: f091f6195a194f38a47f8b329bbd9255),\n",
       " ItemNode(id: 7f7c4245f03445e782e9aa4a4d06221d),\n",
       " ItemNode(id: 07a05ca8a10843aba797076d40ca8f36),\n",
       " ItemNode(id: https://oceans1.arcgis.com/arcgis/rest/services/USA_Drilling_Platforms/FeatureServer/0),\n",
       " ItemNode(id: e26f2752e86d4a8dad52ea75501480f0),\n",
       " ItemNode(id: aecf7fd35dca43fe80fc67b60fb73516),\n",
       " ItemNode(id: ab924202cc404af58b41efcf99b0aafa),\n",
       " ItemNode(id: 1c735ebaed8d48b5bfd6fcfcd35eb3d1),\n",
       " ItemNode(id: a5846d8e82834f4398fb54e0ef0db0c5),\n",
       " ItemNode(id: bbf872949f2f43a6921e716f7fbe1d72),\n",
       " ItemNode(id: 1c80207bf5384974994ad4a13abf4556)]"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "no_item_nodes = [node for node in new_graph.all_items() if not node.item]\n",
    "no_item_nodes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f621f913-9b8c-47e0-b7d3-619410223d9c",
   "metadata": {},
   "source": [
    "As we can see, we now have a list of nodes where the ID's don't lead to a portal item. There is one anomaly here: what appears to be a service that just doesn't have an associated portal item, but still may be valid. We can add some separate logic to ensure we test any URL for valid data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "5d0a224d-de59-4b6f-ad86-b209c5a91340",
   "metadata": {},
   "outputs": [],
   "source": [
    "from arcgis.layers import Service\n",
    "updated_no_item = []\n",
    "for node in no_item_nodes:\n",
    "    if \"https://\" in node.id:\n",
    "        try:\n",
    "            serv = Service(node.id)\n",
    "            if not serv:\n",
    "                raise\n",
    "        except:\n",
    "            updated_no_item.append(node)\n",
    "    else:\n",
    "        updated_no_item.append(node)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd4c5d32-2f52-44d0-a59d-c5beaec43493",
   "metadata": {},
   "source": [
    "Given this list of items with ID's that lead nowhere, we can grab the node for any one of them and do what we did above- see which org items contain or require them. From there, we can figure out how to fix it- one option is using the `remap_data()` function, documented [here](/python/latest/api-reference/arcgis.gis.toc.html#arcgis.gis.Item.remap_data)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "de01da8b-84f6-4f46-864d-ceb41b31e9e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ItemNode(id: e6430fd93abe46ccaf2a8e31b5a35c80, item: AZ Vehicle Incidents)]"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "broken_node = updated_no_item[0]\n",
    "broken_node.contained_by()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "c4f3a39d-9c0b-4659-8705-6b114ca3a635",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[ItemNode(id: e6430fd93abe46ccaf2a8e31b5a35c80, item: AZ Vehicle Incidents),\n",
       " ItemNode(id: d3b24b91f2c3432fbb5b7d2862f7525d, item: TestInstantApp),\n",
       " ItemNode(id: 7259119a69044ae4aebd3e4cd338321f, item: AZ Vehicle App)]"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "broken_node.required_by()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "014807cf-c9e1-442f-9d74-22b7a215e99a",
   "metadata": {},
   "source": [
    "### Sorting Items by Degree, Type, and More\n",
    "\n",
    "Finally, let's put ourselves in the shoes of an organization admin that wants to learn about the items in their org: which items have the most dependencies, and which ones are needed by the most items? Which ones have the most broken dependencies? Let's take a look at how we can capitalize on some graph logic and networkx tricks to gain insights into our organization's content."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2e3cf87-7861-4b60-ae6a-55fb62215042",
   "metadata": {},
   "source": [
    "We'll start basic: just identify which nodes have the highest _degree_, or number of direct relationships (\"contains\"/\"contained by\"). Since a degree can refer to either direction relationship, we specify the _out_ degree or _in_ degree, which in an `ItemGraph` will show the amount of each node's `contains()` and `contained_by()`, respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "e0de0bbf-eacd-4791-97ed-a7e948adca7b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sort_degrees(direction = \"out\", descending = True, result_count = 50):\n",
    "    node_degrees = new_graph.out_degree()\n",
    "    if direction == \"in\":\n",
    "        node_degrees = new_graph.in_degree()\n",
    "    nodes_sorted = sorted(node_degrees, key=lambda item: item[1], reverse=descending)\n",
    "    if result_count and result_count > len(nodes_sorted):\n",
    "        result_count = len(nodes_sorted)\n",
    "    for node, degree in nodes_sorted[:result_count]:\n",
    "        graph_node = new_graph.get_node(node)\n",
    "        if graph_node.item:\n",
    "            print(f\"Title: {graph_node.item.title}, Type: {graph_node.item.type}, Degree: {degree}\")\n",
    "        else:\n",
    "            print(f\"ID: {node}, Degree: {degree}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "6975d920-3314-484e-8a6e-af5929b18d42",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title: New York Enriched Top Areas of Interest, Type: Web Map, Degree: 158\n",
      "Title: New York Enriched Top Areas of Interest, Type: Web Map, Degree: 158\n",
      "Title: DevTechSummit2025-copy-1745540837450, Type: Hub Site Application, Degree: 13\n",
      "Title: My Site in Enterprise - new, Type: Hub Site Application, Degree: 12\n",
      "Title: San Diego Parrot Sightings, Type: Form, Degree: 6\n",
      "Title: Discover Green Spaces and Wildlife in Berlin, Type: Web Mapping Application, Degree: 6\n",
      "Title: AZ Vehicle Incidents, Type: Web Map, Degree: 4\n",
      "Title: Living Atlas Map, Type: Web Map, Degree: 4\n",
      "Title: SimpleWebMap, Type: Web Map, Degree: 4\n",
      "Title: Arkansas Hospitals, Type: Web Map, Degree: 4\n",
      "Title: TestInstantApp, Type: Web Mapping Application, Degree: 3\n",
      "Title: map test, Type: Web Map, Degree: 3\n",
      "Title: Cycling Explorer, Type: Web Map, Degree: 3\n",
      "Title: AZ and NM Cities, Type: Web Map, Degree: 3\n",
      "Title: Jy Survey 123 Connect, Type: Form, Degree: 3\n",
      "Title: Jy Survey 123 Connect, Type: Form, Degree: 3\n",
      "Title: map test, Type: Web Map, Degree: 3\n",
      "Title: Group Layer Map Test, Type: Web Map, Degree: 3\n",
      "Title: Map Series 884411, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 213975, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 959005, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 537579, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 845552, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 836403, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 639470, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 816182, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 398285, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 985608, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 287154, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 396347, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 684806, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 709821, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 587161, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 255073, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 553493, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 329174, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 37166, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 261798, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 395417, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 326103, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 116930, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 222445, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 432118, Type: Web Mapping Application, Degree: 3\n",
      "Title: USA WebMap, Type: Web Map, Degree: 3\n",
      "Title: AZ Vehicle App, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 692346, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 772573, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 254278, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 19528, Type: Web Mapping Application, Degree: 3\n",
      "Title: Map Series 238550, Type: Web Mapping Application, Degree: 3\n"
     ]
    }
   ],
   "source": [
    "# find which items contain the most other items\n",
    "sort_degrees(direction = \"out\", descending = True, result_count = 50)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "6c7a1bc2-b888-4cd0-8d8e-8cf5c9e30ab5",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ID: bf08d46ab087435aa4afbc62092223cb, Degree: 153\n",
      "ID: 123hehethiswontwork, Degree: 153\n",
      "ID: 7f7c4245f03445e782e9aa4a4d06221d, Degree: 33\n",
      "ID: 07a05ca8a10843aba797076d40ca8f36, Degree: 33\n",
      "Title: World Topographic Map, Type: Vector Tile Service, Degree: 8\n",
      "Title: Web Map 400800, Type: Web Map, Degree: 7\n",
      "Title: Outline Map, Type: Web Map, Degree: 7\n",
      "Title: Newspaper (WGS84), Type: Vector Tile Service, Degree: 5\n",
      "Title: OpenStreetMap Streets with Relief, Type: Vector Tile Service, Degree: 5\n",
      "ID: 2, Degree: 3\n",
      "Title: Esri_Regional_Offices_US, Type: File Geodatabase, Degree: 3\n",
      "Title: Jy Survey 123 Connect, Type: Feature Service, Degree: 3\n",
      "Title: Jy Survey 123 Connect, Type: Feature Service, Degree: 3\n",
      "Title: AZ Vehicle Incidents, Type: Web Map, Degree: 2\n",
      "Title: Basic, Type: Web Mapping Application, Degree: 2\n",
      "Title: AGO World Geocoder (arcgis_python), Type: Geocoding Service, Degree: 2\n",
      "ID: 2fe20a161c514e16b805a21a7e2d636b, Degree: 2\n",
      "ID: 15efb8c0d9e3447782789592f432fc1a, Degree: 2\n",
      "ID: bda2f1dc3c824c3e97f4a682554177cf, Degree: 2\n",
      "ID: d60affb34dd948a1b973da076830ad00, Degree: 2\n",
      "ID: f32924d7b16f41d78839dba3b943b08c, Degree: 2\n",
      "ID: 9f91d4c34f194da793c8573b24a751a9, Degree: 2\n",
      "ID: 91fa101048bb4855970f7d004a4542ce, Degree: 2\n",
      "ID: 6e02b538bea841ed858ef9f52709b655, Degree: 2\n",
      "Title: National Weather Service Day 1, Type: WMS, Degree: 2\n",
      "Title: Enhanced Contrast Dark Map (WGS84), Type: Web Map, Degree: 2\n",
      "ID: 44c3348139a84423b4a46074a104efdf, Degree: 2\n",
      "Title: Test Case 12305 Survey, Type: Feature Service, Degree: 2\n",
      "Title: Test Case 232 A, Type: Feature Service, Degree: 2\n",
      "Title: USA_Major_Cities_Data, Type: Feature Service, Degree: 2\n",
      "Title: San Diego Parrot Sightings, Type: Feature Service, Degree: 2\n",
      "Title: DevSummit Theme, Type: StoryMap Theme, Degree: 2\n",
      "Title: ca_public_schools, Type: Feature Service, Degree: 2\n",
      "ID: cdf23b869e7649469759cf756c1d43f0, Degree: 2\n",
      "ID: a5f11273b85d40adbd7cf9a162f81ef2, Degree: 2\n",
      "ID: 08a9b819b9e04de9a68418f2b225ec6a, Degree: 2\n",
      "ID: f265c79c47a3413b8b8f711909f03fe2, Degree: 2\n",
      "ID: 819ee7ddbf5848889effd0fa6b039a51, Degree: 2\n",
      "ID: 8548e23d8b1a478eaf2246e6fc3b31b9, Degree: 2\n",
      "ID: f97edbe48af7427f8604f20320e2de52, Degree: 2\n",
      "ID: b66792b3bb004fa8997fcfcef991e984, Degree: 2\n",
      "ID: 9204269c8e714500a565a3ddf055825d, Degree: 2\n",
      "ID: 28dae0b8f1c44814b281b71752453c61, Degree: 2\n",
      "ID: d15c117e60dd4fe299ec03a379c9caf8, Degree: 2\n",
      "ID: 3b6d38a456164adea4c061a2a51d89b1, Degree: 2\n",
      "ID: a12fcbe07c8d41f1b6981f33a10d1d0c, Degree: 2\n",
      "ID: ae4bea7c35824bf1ae571783142dc97d, Degree: 2\n",
      "ID: 8e969d9adb7f485c88a8350d317e8c9b, Degree: 2\n",
      "ID: 493db5d6832b44a581547a8df8c3907c, Degree: 2\n",
      "ID: ebe640ee5d344bea9fca7bfa4d80bb3a, Degree: 2\n"
     ]
    }
   ],
   "source": [
    "# find which items are contained by the most other items\n",
    "sort_degrees(direction = \"in\", descending = True, result_count = 50)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc04967d-5a99-47ef-bb95-85ee2e09b7c6",
   "metadata": {},
   "source": [
    "We can similarly define a function that will do that for the \"deep\" degrees- finding which items have the most recursive dependencies or items dependent upon them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "49a220a2-87e7-42c9-ab0a-da043e689aba",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sort_deep_degrees(direction = \"out\", descending = True, result_count = 50):\n",
    "    if direction == \"in\":\n",
    "        nodes_weighted = [(node, len(node.required_by())) for node in new_graph.all_items()]\n",
    "    else:\n",
    "        nodes_weighted = [(node, len(node.requires())) for node in new_graph.all_items()]\n",
    "    nodes_sorted = sorted(nodes_weighted, key=lambda item: item[1], reverse = descending)\n",
    "    if result_count and result_count > len(nodes_sorted):\n",
    "        result_count = len(nodes_sorted)\n",
    "    for node, degree in nodes_sorted[:result_count]:\n",
    "        if node.item:\n",
    "            print(f\"Title: {node.item.title}, Type: {node.item.type}, Degree: {degree}\")\n",
    "        else:\n",
    "            print(f\"ID: {node.id}, Degree: {degree}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "f03263b2-d5a1-4097-a36e-f77e7a8ce65f",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Title: Testing Copy Content, Type: StoryMap, Degree: 159\n",
      "Title: New York Enriched Top Areas of Interest, Type: Web Map, Degree: 158\n",
      "Title: New York Enriched Top Areas of Interest, Type: Web Map, Degree: 158\n",
      "Title: DS-Page1-copy-1745540879568, Type: Hub Page, Degree: 14\n",
      "Title: DevTechSummit2025-copy-1745540837450, Type: Hub Site Application, Degree: 13\n",
      "Title: My Site in Enterprise - new, Type: Hub Site Application, Degree: 12\n",
      "Title: TestInstantApp, Type: Web Mapping Application, Degree: 8\n",
      "Title: San Diego Parrot Sightings, Type: Form, Degree: 8\n",
      "Title: All About Arizona and New Mexico, Type: StoryMap, Degree: 8\n",
      "Title: AZ Vehicle App, Type: Web Mapping Application, Degree: 8\n",
      "Title: Discover Green Spaces and Wildlife in Berlin, Type: Web Mapping Application, Degree: 7\n",
      "Title: Formerly Local, Now Global Experience, Type: Web Experience, Degree: 6\n",
      "Title: AZ Vehicle Incidents, Type: Web Map, Degree: 5\n",
      "Title: AZ and NM Cities, Type: Web Map, Degree: 5\n",
      "Title: Ruff Ruff, Type: StoryMap, Degree: 5\n",
      "Title: Group Layer Map Test, Type: Web Map, Degree: 5\n",
      "Title: LimerickStoryMap, Type: StoryMap, Degree: 5\n",
      "Title: test_cat_selector, Type: Dashboard, Degree: 5\n",
      "Title: Copy this story, Type: StoryMap, Degree: 4\n",
      "Title: map test, Type: Web Map, Degree: 4\n",
      "Title: Cycling Explorer, Type: Web Map, Degree: 4\n",
      "Title: Offline Cloning Draft Test, Type: Web Experience, Degree: 4\n",
      "Title: Jy Survey 123 Connect, Type: Form, Degree: 4\n",
      "Title: Living Atlas Map, Type: Web Map, Degree: 4\n",
      "Title: Jy Survey 123 Connect, Type: Form, Degree: 4\n",
      "Title: California Demo, Type: StoryMap, Degree: 4\n",
      "Title: Offline Cloning Draft Test, Type: Web Experience, Degree: 4\n",
      "Title: California Demo, Type: StoryMap, Degree: 4\n",
      "Title: California Demo, Type: StoryMap, Degree: 4\n",
      "Title: California Demo, Type: StoryMap, Degree: 4\n",
      "Title: Offline Cloning Draft Test, Type: Web Experience, Degree: 4\n",
      "Title: Offline Cloning Draft Test, Type: Web Experience, Degree: 4\n",
      "Title: California Demo, Type: StoryMap, Degree: 4\n",
      "Title: Offline Cloning Draft Test, Type: Web Experience, Degree: 4\n",
      "Title: SimpleWebMap, Type: Web Map, Degree: 4\n",
      "Title: Arkansas Hospitals, Type: Web Map, Degree: 4\n",
      "Title: Nothing Funny About This Test - updated PR, Type: Web Experience, Degree: 3\n",
      "Title: Hilarious Little Test, Type: Web Experience, Degree: 3\n",
      "Title: Hilarious Little Test2, Type: Web Experience, Degree: 3\n",
      "Title: Hilarious Little Test - updated PR, Type: Web Experience, Degree: 3\n",
      "Title: Hilarious Little Test - updated PR1, Type: Web Experience, Degree: 3\n",
      "Title: No Image Test, Type: Web Experience, Degree: 3\n",
      "Title: Nothing Funny About This Test, Type: Web Experience, Degree: 3\n",
      "Title: No Image Test, Type: Web Experience, Degree: 3\n",
      "Title: Nothing Funny About This Test, Type: Web Experience, Degree: 3\n",
      "Title: Esri Offices, Fancy, Type: Web Map, Degree: 3\n",
      "Title: Esri Offices, Fancy, Type: Web Map, Degree: 3\n",
      "Title: TerrainMap, Type: Web Map, Degree: 3\n",
      "Title: TerrainMap, Type: Web Map, Degree: 3\n",
      "Title: TerrainMap, Type: Web Map, Degree: 3\n"
     ]
    }
   ],
   "source": [
    "sort_deep_degrees()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2e9dc54-59e5-4503-8ba8-267dbe9e6e25",
   "metadata": {},
   "source": [
    "Finally, we can construct a custom function that can do the two prior bits, plus sort items by type, and define the result count. This allows us to easily filter and search  our org's items with additional context on the weight of their dependencies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "07dea0a0-ab93-45f1-bfde-cb13573c393d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def filter_nodes(direction = \"out\", deep = False, descending = True, item_type = None, result_count: int = None):\n",
    "    if item_type:\n",
    "        nodes_filtered = [node for node in new_graph.all_items() if node.item and node.item.type == item_type]\n",
    "    else:\n",
    "        nodes_filtered = new_graph.all_items()\n",
    "    if direction == \"in\" and deep:\n",
    "        nodes_weighted = [(node, len(node.required_by())) for node in nodes_filtered]\n",
    "    elif direction == \"out\" and deep:\n",
    "        nodes_weighted = [(node, len(node.requires())) for node in nodes_filtered]\n",
    "    elif direction == \"in\" and not deep:\n",
    "        nodes_weighted = [(node, len(node.contained_by())) for node in nodes_filtered]\n",
    "    else:\n",
    "        nodes_weighted = [(node, len(node.contains())) for node in nodes_filtered]\n",
    "    nodes_sorted = sorted(nodes_weighted, key=lambda item: item[1], reverse = descending)\n",
    "    if result_count and result_count > len(nodes_sorted):\n",
    "        result_count = len(nodes_sorted)\n",
    "    for node, degree in nodes_sorted[:result_count]:\n",
    "        if node.item:\n",
    "            print(f\"Title: {node.item.title}, Type: {node.item.type}, Degree: {degree}\")\n",
    "        else:\n",
    "            print(f\"ID: {node.id}, Degree: {degree}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83550b88-950f-48b8-8c39-bb9364540e52",
   "metadata": {},
   "source": [
    "## Part 3: Automating this Notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b57d4e60-b053-4136-a47b-59b442080af8",
   "metadata": {},
   "source": [
    "Everything we've done in this notebook is purely informative- no changes, additions, or deletions to org items were done. All we've done is update and manipulate or ItemGraph in memory and written out to file. So what does this mean? \n",
    "\n",
    "This means that you can download this very notebook and run it for yourself. Keeping this notebook run on a consistent timeframe will provide you with an up-to-date graph to analyze your org items. ArcGIS Notebooks, in both ArcGIS Online and ArcGIS Enterprise, provide us with an easy way to schedule automation of notebooks. Let's take a look how.\n",
    "\n",
    "### Scheduling a Task\n",
    "\n",
    "A \"task\" is a command to run a given notebook. You can create scheduled tasks that dictate when and how often to run a notebook. Each time the notebook is run according to the schedule you set, the site opens a new container and runs the notebook without user control.\n",
    "\n",
    "To access this function, open the \"Tasks\" pane in the notebook editor. You can schedule it to run just once in the future or on a recurring basis— from once every 15 minutes to once every 6 months.\n",
    "\n",
    "Once you click on the Tasks pane, you will be prompted to provide a title for the Task."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81ad1aee-9219-4490-a9bf-eda1ab7907d7",
   "metadata": {},
   "source": [
    "![Image](https://github.com/user-attachments/assets/0e374e87-e08d-4789-9cb8-e6a387ac18f6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ac566c6-cdca-4a13-abb0-78c0c460fec8",
   "metadata": {},
   "source": [
    "You can also set other specific parameters for when and how often you would like for this notebook to run."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d36908b0-1cf0-479b-8356-9a89c0c65535",
   "metadata": {},
   "source": [
    "![parameters](https://github.com/user-attachments/assets/551a68f5-976a-47ea-83c1-257c99643ffd)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2cdebf2-1d01-4ea5-8001-dd15a79963ad",
   "metadata": {},
   "source": [
    "Once you have created this task, you can find it under the Tasks pane, and can pause, delete or edit it as necessary. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f47c1284-c735-4688-9618-94fa954b9d5f",
   "metadata": {},
   "source": [
    "![tasks](https://github.com/user-attachments/assets/975a6137-1cf7-4e6c-ae1c-85342b534d7f)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79eb8bb0-cf28-43dd-b8c0-07fba4addfc9",
   "metadata": {},
   "source": [
    "> Note: For Notebooks in ArcGIS Online, you can have a maximum of 10 active tasks across all your notebooks. If you pause some of your active tasks, you will be allowed to create more tasks until you reach 10 active tasks again. For Notebooks in ArcGIS Enterprise, the default number of maximum active tasks is set at 20. Administrators of an organization have the privilege to [change that limit](https://developers.arcgis.com/rest/enterprise-administration/portal/limits-system). "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
